<?php

namespace app\admin\controller;

use app\admin\model\UserNewsLog;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 消息列管理
 *
 * @icon fa fa-circle-o
 */
class News extends Backend
{

    /**
     * News模型对象
     * @var \app\admin\model\News
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\News;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("sendTypeList", $this->model->getSendTypeList());
        $this->view->assign("isSendList", $this->model->getIsSendList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                if($params['send_type']==1){
                    $params['user_ids'] = "";
                }elseif($params['send_type']==2){
                    if(preg_match_all("/[1-9]+[0-9]*/",$params['user_ids'],$arr)){
                        if($arr && is_array($arr) && $arr[0]){
                            $user_ids = [];
                            foreach ($arr[0] as $arr_val){
                                $user_id = (int)$arr_val;
                                if($user_id>0 && !in_array($user_id,$user_ids)){
                                    $user_ids[] = $user_id;
                                }
                            }
                            $params['user_ids'] = $user_ids?"|".join("|",$user_ids)."|":"";
                        }else{
                            $this->error("请填写用户id");
                        }
                    }else{
                        $this->error("请填写用户id");
                    }
                }

                $reward_arr = [];
                if(isset($params['reward']) && $params['reward'] && is_array($params['reward'])){
                    $n = 0;
                    foreach ($params['reward'] as $k=>$reward){
                        $num = (int)($params['num'][$k]??0);
                        if(empty($reward) || $num<1){
                            continue;
                        }
                        $n ++;
                        $reward_arr[] = [
                            'reward'=>$reward,
                            'num'=>$num
                        ];
                        if($n>=5){
                            break;
                        }
                    }
                }
                $params['reward'] = $reward_arr?json_encode($reward_arr,JSON_UNESCAPED_UNICODE):"";
                $params['admin_id'] = $this->auth->id;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $nowTime = time();
                    if($params['is_send']==1){
                        $params['send_time'] = $nowTime;
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $news_id = $this->model->id;
                    if($params['is_send']==1){
                        if($params['send_type']==1){
                            $user_list = Db::name('users')->field(['id'])->select();
                            $news_log = [];
                            foreach ($user_list as $user_list_val){
                                $news_log[]=[
                                    'user_id'=>$user_list_val['id'],
                                    'is_get'=>0,
                                    'is_read'=>0,
                                    'news_id'=>$news_id
                                ];
                            }

                            $userNewsLogModel = new UserNewsLog();
                            $userNewsLogModel->saveAll($news_log);
                        }elseif($params['send_type']==2 && $params['user_ids']){
                            $user_ids = explode("|",trim($params['user_ids'],"|"));
                            $news_log = [];
                            foreach ($user_ids as $user_ids_val){
                                $news_log[]=[
                                    'user_id'=>$user_ids_val,
                                    'is_get'=>0,
                                    'is_read'=>0,
                                    'news_id'=>$news_id
                                ];
                            }
                            $userNewsLogModel = new UserNewsLog();
                            $userNewsLogModel->saveAll($news_log);
                        }
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $prop_list = Db::table('prop')->field(['id','name','coin','code'])->select();
        $skin_list = Db::table('skin')->where("type","<>","farm")->field(['id','name','coin','code'])->select();
        $data_list = [];
        foreach ($prop_list as $val){
            $data_list['prop='.$val['code']]=$val['name']." --- 金币价格:".$val['coin'];
        }
        foreach ($skin_list as $val){
            $data_list['skin='.$val['code']]=$val['name']." --- 金币价格:".$val['coin'];
        }
        $data_list['coin'] = "金币";
        $data_list['coin1'] = "钻石";
        $this->assign("data_list",$data_list);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $news_id = $ids;
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if($params['send_type']==1){
                    $params['user_ids'] = "";
                }elseif($params['send_type']==2){
                    if(preg_match_all("/[1-9]+[0-9]*/",$params['user_ids'],$arr)){
                        if($arr && is_array($arr) && $arr[0]){
                            $user_ids = [];
                            foreach ($arr[0] as $arr_val){
                                $user_id = (int)$arr_val;
                                if($user_id>0 && !in_array($user_id,$user_ids)){
                                    $user_ids[] = $user_id;
                                }
                            }
                            $params['user_ids'] = $user_ids?"|".join("|",$user_ids)."|":"";
                        }else{
                            $this->error("请填写用户id");
                        }
                    }else{
                        $this->error("请填写用户id");
                    }
                }

                $reward_arr = [];
                if(isset($params['reward']) && $params['reward'] && is_array($params['reward'])){
                    $n = 0;
                    foreach ($params['reward'] as $k=>$reward){
                        $num = (int)($params['num'][$k]??0);
                        if(empty($reward) || $num<1){
                            continue;
                        }
                        $n ++;
                        $reward_arr[] = [
                            'reward'=>$reward,
                            'num'=>$num
                        ];
                        if($n>=5){
                            break;
                        }
                    }
                }
                $params['reward'] = $reward_arr?json_encode($reward_arr,JSON_UNESCAPED_UNICODE):"";
                $params['admin_id'] = $this->auth->id;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $nowTime = time();
                    if($params['is_send']==1){
                        $params['send_time'] = $nowTime;
                    }
                    $result = $row->allowField(true)->save($params);
                    if($params['is_send']==1){
                        if($params['send_type']==1){
                            $user_list = Db::name('users')->field(['id'])->select();
                            $news_log = [];
                            foreach ($user_list as $user_list_val){
                                $news_log[]=[
                                    'user_id'=>$user_list_val['id'],
                                    'is_get'=>0,
                                    'is_read'=>0,
                                    'news_id'=>$news_id
                                ];
                            }
                            $userNewsLogModel = new UserNewsLog();
                            $userNewsLogModel->saveAll($news_log);
                        }elseif($params['send_type']==2 && $params['user_ids']){
                            $user_ids = explode("|",trim($params['user_ids'],"|"));
                            $news_log = [];
                            foreach ($user_ids as $user_ids_val){
                                $news_log[]=[
                                    'user_id'=>$user_ids_val,
                                    'is_get'=>0,
                                    'is_read'=>0,
                                    'news_id'=>$news_id
                                ];
                            }
                            $userNewsLogModel = new UserNewsLog();
                            $userNewsLogModel->saveAll($news_log);
                        }
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $prop_list = Db::table('prop')->field(['id','name','coin','code'])->select();
        $skin_list = Db::table('skin')->where("type","<>","farm")->field(['id','name','coin','code'])->select();
        $data_list = [];
        foreach ($prop_list as $val){
            $data_list['prop='.$val['code']]=$val['name']." --- 金币价格:".$val['coin'];
        }
        foreach ($skin_list as $val){
            $data_list['skin='.$val['code']]=$val['name']." --- 金币价格:".$val['coin'];
        }
        $data_list['coin'] = "金币";
        $data_list['coin1'] = "钻石";

        $reward_list = $row->reward?json_decode( $row->reward,true):[];
        $user_ids = $row['user_ids']?explode("|",trim($row['user_ids'],"|")):[];
        $row['user_ids'] = $user_ids?join(" ",$user_ids):"";
        $this->assign("reward_list",$reward_list);
        $this->assign("data_list",$data_list);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


}
